package logic

import (
	"common/model"
	"common/pkg"
	"common/utils"
	"context"
	"errors"
	"fmt"
	"opd_server/proto/opd"
	"strconv"
	"time"
)

func (o OpdService) OutpatientRegistration(ctx context.Context, req *opd.OutpatientRegistrationRequest) (*opd.OutpatientRegistrationResponse, error) {
	var doctor model.Doctors
	info, err := doctor.ByInfo(req.DoctorId)
	if err != nil {
		return nil, err
	}
	if info.Id == 0 {
		return nil, errors.New("没有该医生")
	}

	text := pkg.SensitiveWords(req.Remarks)
	if text != "合规" {
		return nil, errors.New(text)
	}

	key := fmt.Sprintf("opd:%s:%d:%d", req.AppointmentDate, req.AppointmentTimePeriod, req.DoctorId)

	lRange, err := utils.LRange(key)
	if err != nil {
		return nil, err
	}
	for _, s := range lRange {
		if s == strconv.Itoa(int(req.UserId)) {
			return nil, errors.New("该用户已预约")
		}
	}

	listLen, err := utils.GetRedisListLen(key)
	if err != nil {
		return nil, err
	}
	if listLen >= 10 {
		return nil, errors.New("该医生该时间段已满")
	}

	parse, err := time.Parse("2006-01-02", req.AppointmentDate)
	if err != nil {
		return nil, errors.New("预约日期格式错误")
	}

	timeNow := time.Now().AddDate(0, 0, 15)
	if parse.After(timeNow) {
		return nil, errors.New("预约日期不能超过15天")
	}

	var registrationType int
	if info.Title == "主任医师" {
		registrationType = 2
	} else {
		registrationType = 1
	}
	var registration = model.Registration{
		PatientId:             int(req.UserId),
		DoctorId:              int(req.DoctorId),
		RegistrationTime:      time.Now(),
		AppointmentDate:       parse,
		AppointmentTimePeriod: int(req.AppointmentTimePeriod),
		RegistrationType:      registrationType,
		RegistrationStatus:    1,
		Remarks:               req.Remarks,
	}
	err = registration.Create()
	if err != nil {
		return nil, err
	}

	err = utils.SetRedisList(key, req.UserId)
	if err != nil {
		return nil, errors.New("挂号失败")
	}

	pay := pkg.NewPay()
	if pay == nil {
		return nil, errors.New("创建支付实例失败")
	}

	orderPrice := strconv.FormatFloat(5.00, 'f', -1, 64)
	var payErr error
	url, payErr := pay.Pay("挂号费用", key+strconv.Itoa(int(req.UserId)), orderPrice)
	if payErr != nil {
		return nil, errors.New("创建支付链接失败")
	}
	return &opd.OutpatientRegistrationResponse{
		Success: url,
	}, nil
}
